package api

import (
	"gfrest/common/base"
	"gfrest/common/ctxkit"
	"gfrest/common/log"
	"gfrest/common/util"
	"gfrest/web/app/service"

	"gfrest/common/code"
	_ "gfrest/common/web_middleware"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gvalid"
)

// AuthController AuthController
type AuthController struct {
}

// login login
// @Summary login
// @Description login
// @Tags auth
// @Param   payload   body    web_middleware.UserLogin    false  "Payload description"
// @success 200 {object} base.Result{} "desc"
// @router /login [post]
func (c *AuthController) login(r *ghttp.Request) {

	r.Response.WriteJson(g.Map{"msg": "test"})
}

// token refresh
// @Summary refresh token
// @Description refresh
// @Tags auth
// @success 200 {object} base.Result{} "desc"
// @router /auth/refresh [get]
// @Security ApiKeyAuth
func (c *AuthController) refresh(r *ghttp.Request) {

	r.Response.WriteJson(g.Map{"msg": "test"})
}

// Logout Logout
// @Summary Logout
// @Description Logout
// @Tags auth
// @router /auth/logout [get]
func (c *AuthController) Logout(r *ghttp.Request) {
	r.Cookie.Remove("jwt-token")

	r.Response.Status = 401
	r.Response.WriteJson(g.Map{"msg": "need login"})
}

type updatePassword struct {
	Password  string `json:"password" v:"password @required|length:6,16|same:password2"`
	Password2 string `json:"password2" v:"password2 @required|length:6,16"`
}

// Customized login parameter validation rules.
var updatePasswordRules = util.StructValidTags(updatePassword{})

// ChangePassword ChangePassword
// @Summary ChangePassword
// @Description ChangePassword
// @Tags auth
// @Param   payload   body    updatePassword    false  "Payload description"
// @success 200 {object} base.Result{} "desc"
// @router /auth/change-password [post]
func (c *AuthController) ChangePassword(r *ghttp.Request) {
	user := ctxkit.GetUser(r.Context())

	obj := updatePassword{}
	if err := r.Parse(&obj); err != nil {
		log.Error(r.Context(), err)
		if v, ok := err.(*gvalid.Error); ok {
			base.Fail(r, code.Errors[code.ERROR_PARAM], v.Maps())
			return
		}
		base.Fail(r, code.Errors[code.ERROR_PARAM], err.Error())
		return
	}
	ok := service.AuthUserService.UpdatePassword(user.Id, obj.Password)
	if !ok {
		base.Fail(r, code.Errors[code.ERROR_DB_UPDATE])

	}
	base.Success(r, g.Map{})
}
